package com.huang.wishstar.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.internet.MimeMessage;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

@Component
public class MyEmail {

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    JavaMailSender javaMailSender;
    @Autowired
    TemplateEngine templateEngine;

    /**
     * 发送验证码
     *
     */
    public String registerMail(String email){

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
//            设置发件人
            mimeMessageHelper.setFrom(from);
//            设置收件人
            mimeMessageHelper.setTo(email);
//            设置邮件主题
            mimeMessageHelper.setSubject("WishStar|用户注册验证邮箱");
            //生成随机数
            String random = randomInteger();

            //使用thymeleaf来生成发送邮件的html，需导入依赖
            Context context = new Context();
            context.setVariable("verifyCode", random);
            String emailContext = templateEngine.process("registerTemplate",context);
//            System.out.println("emailContext="+emailContext);
            //设置验证码的样式，简单语句可以这么整
//            mimeMessageHelper.setText("<font style='color:green'>"+random+"</font>",true);
            mimeMessageHelper.setText(emailContext,true);
            return random;

        }catch (MessagingException e) {
            return "error";
        }
        finally {
            try {
                javaMailSender.send(mimeMessage);
            }catch (MailSendException e){
                Set<String> tmpInvalidMails = getInvalidAddress(e);
                return "error";
            }

        }

    }

    public String updatePwdMail(String email) {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
//            设置发件人
            mimeMessageHelper.setFrom(from);
//            设置收件人
            mimeMessageHelper.setTo(email);
//            设置邮件主题
            mimeMessageHelper.setSubject("WishStar|修改密码验证邮箱");
            //生成随机数
            String random = randomInteger();

            //使用thymeleaf来生成发送邮件的html
            Context context = new Context();
            context.setVariable("verifyCode", random);
            String emailContext = templateEngine.process("updatePwdTemplate",context);
//            System.out.println("emailContext="+emailContext);
            //设置验证码的样式，简单语句可以这么整
//            mimeMessageHelper.setText("<font style='color:green'>"+random+"</font>",true);
            mimeMessageHelper.setText(emailContext,true);
            javaMailSender.send(mimeMessage);
            return random;

        } catch (MessagingException e) {
            e.printStackTrace();
            return "error";
        }


    }
    /**
     * 生成随机验证码
     *
     * @return
     */
    private String randomInteger() {
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        //生成6位的随机数
        for (int i = 0;i<6;i++){
            int i1 = random.nextInt(10);
            stringBuffer.append(i1);
        }
        return stringBuffer.toString();
    }

    private Set<String> getInvalidAddress(MailSendException e){
        Set<String> mails = new HashSet<>();
        for(Exception exception: e.getFailedMessages().values()){
            if(exception instanceof SendFailedException){
                for(Address address: ((SendFailedException) exception).getInvalidAddresses()){
                    mails.add(address.toString());
                }
            }
        }
        return mails;
    }

}

